import BuildConfig from '../build/BuildConfig'
// import { getPayModule } from 'src/components/provider.vue'
// import { ESShaanxiPayModule } from '@extscreen/es-shaanxi-pay'
import { createESPayModule, ESPayModule } from '@extscreen/es3-shanxi-pay'
import { createESContentProviderModule } from '@extscreen/es3-content-provider'

import { probe } from './probe'

// import { useESToast } from '@extscreen/es3-core'

// const toast = useESToast()

const provider = createESContentProviderModule()

// 用户鉴权
/**
 * @param {*} globalApi   全局api 只能从页面获取该对象
 * @param {*} successFn 成功回调
 * @param {*} failFn 失败回调
 * @param {*} goOrderPage 未订购是否直接跳转订购(默认是)
 */
async function authorize(globalApi, successFn, failFn, goOrderPage = true) {
  const uid = await localStorage.getString('userId', '')
  const userAccount = await localStorage.getString('userAccount', '')
  const mac = await localStorage.getString('mac', '')

  // 点播产品编码：ye_db_001
  // 包月产品编码：ye_by_001

  const _params = {
    account: userAccount,
    // contentId: mediaData['playUrl'],
    stbId: mac,
    productCode: getProductCode(),
    cId: BuildConfig.cid,
    userId: uid
  }

  console.log('122 _params >>>', _params)

  globalApi
    .authSXYD(_params)
    .then((res) => {
      console.log('122 鉴权结果', res)
      if (res.data.code === '00') {
        // 是否有订购过的包
        let isOrder = false

        if (res.data.result) {
          let productList = res.data.result
          productList.forEach((item) => {
            let product = JSON.parse(item)
            if (product.isOrder) {
              isOrder = true
            }
          })
        }

        if (res.data.allPassed) {
          // 免鉴权
          isOrder = true
        }

        if (isOrder) {
          console.log('已订购')
          successFn()
        } else {
          console.log('未订购')
          failFn()
          if (goOrderPage) {
            // 去支付
            toPay(globalApi)
          }
        }
      } else {
        console.log('鉴权失败')
        failFn()
      }
    })
    .catch((err) => {
      console.log('122 鉴权 error', err)
    })
}

async function toPay(globalApi) {
  console.log('33 enter pay')
  let user_token = await localStorage.getString('user_token', '')
  let userId = await localStorage.getString('userId', '')
  let userAccount = await localStorage.getString('userAccount', '')
  let currentMediaJSON = await localStorage.getString('currentMedia', '')
  let currentMedia = JSON.parse(currentMediaJSON)
  console.log('33 pay currentMedia >>>', currentMedia)
  let params = {
    account: userAccount,
    userToken: user_token.split(' ')[1],
    productID: getProductCode(),
    cid: BuildConfig.cid,
    userId: userId
    // authType: '',
    // contentID: '',
    // serviceID: '',
    // remark: '',
    // fromType: 1,
    // returnUrl: '',
    // notifyUrl: '',
    // price: 1,
    // result: 1,
    // snNo: '',
    // adContentId: '',
    // adContentName: '',
    // cdrtype: '',
    // recSourceId: '',
    // stbID: '',
    // faceType: '',
    // isMatchID: '',
    // AREACODE: '',
    // productList: [
    //   {
    //     productCode: '',
    //     productPrice: 1,
    //     productUnit: '',
    //     productCount: 1
    //   }
    // ],
    // mediaId: '',
    // title: '',
    // diversionFST: '',
    // orderMode: 1,
    // continueType: 1,
  }
  console.log('123 创建订单 params', params)

  // 创建订单
  globalApi.createOrderSXYD(params).then((res) => {
    console.log('122 创建订单结果', res)
    if (res.data.orderNo) {
      let orderParams = {
        productCode: getProductCode(),
        stbId: userAccount,
        orderNo: res.data.orderNo,
        transId: res.data.transId,
        account: userAccount,
        payMode: '9', // 默认方式
        // notifyUrl: BuildConfig.requestBaseUrl + '/api/order/shanxi/payCallbackSXYD', //
        notifyUrl: res.data.content,
        backUrl: 'http://szydzdy.holyblade.com:8500/OTTGameHall_YJS_SXYD/Order/BackPage.aspx',
        diversionCode: currentMedia.playUrl.split(';')[0], // 节目编码
        diversionName: currentMedia.title, // 节目名称
        isTouch: '0', // 是否触屏：0否 1是
        cpid: '21022'
      }
      console.log('123 唤起支付 orderParams', orderParams)
      console.log('123 唤起支付 orderParams', JSON.stringify(orderParams))

      // todo 订购埋点
      // probe.order({
      //   productId: '', // 产品包 ID
      //   productName: '', // 产品包名称
      //   orderContentType: 'VIDEO', // 订购内容类型  VIDEO: 视频类  SUB_APP: 子应用类
      //   orderOperateType: 'PRODUCT_IN', // 操作类型    'PRODUCT_IN':进入产品包列表  'PRODUCT_CHOOSE':产品包选择 'OTHER':其它 'ORDER_COMPLETE': 订购完成
      //   orderResultType: 'UNKNOWN', // 支付结果  'SUCCESS':成功  'FAIL':失败   'UNKNOWN':未知
      //   subAppPackageName: '', // 产品包 ID
      //   subAppName: '', // 产品包名称
      //   albumId: '', // 专辑 Id
      //   albumName: '', // 专辑名称
      //   videoId: currentMedia.playUrl.split(';')[0], // 视频 Id
      //   videoName: currentMedia.title, // 视频名称
      //   channelId: '', // 频道 Id
      //   channelName: '', // 频道名称
      //   liveChannelCode: '', // 直播频道 Code
      //   liveChannelName: '', // 直播频道名称
      //   liveProgramName: '', // 节目名称 (栏目名称)
      //   productType: 'CONTINUOUS_MONTHLY' // 产品包类型  'SINGLE_POINT':单点 'TIME_INTERVAL' :包时段  'CONTINUOUS_MONTHLY'：连续包月
      // })

      // {"productCode":"ye_by_001","stbId":"6CC242AA4E83","orderNo":"OHZZY202501060611550000000079012","transId":"THZZY202501060611550000000079012","account":"6CC242AA4E83","payMode":"9","notifyUrl":"http://36.133.100.251:8090/aimxd-webapi-online//api/order/shanxi/payCallbackSXYD","backUrl":"http://szydzdy.holyblade.com:8500/OTTGameHall_YJS_SXYD/Order/BackPage.aspx"}
      const payModule: ESPayModule = createESPayModule()

      // payModule.toPay('ye_service001', '2499215r576ss8s95ii6s2ei7e3paa09', orderParams).then(
      payModule.toPay('1047', '64srr6280r7ie3er4sr9s19iia3440s8', orderParams).then(
        (res) => {
          console.log('支付结果res', res)
        },
        (error) => {
          console.log('支付error', error)
        }
      )
    }
  })
}

// 获取计费点信息
function getProductCode() {
  let products = [
    {
      name: '爱家互动-限时优惠',
      type: '包月',
      code: 'GITV_AJHD_XSYH',
      price: '2990'
    },
    {
      name: '爱家互动-首月一元',
      type: '包月',
      code: 'GITV_AJHDNB_SYYY',
      price: '100'
    },
    {
      name: '爱家互动-融合年包',
      type: '包月',
      code: 'GITV_AJHDRH_NB',
      price: '1500'
    }
  ]
  return products.map((item) => item.code).join(',')
}

// 统一媒资信息
function setupMedia(mediaData) {
  console.log('mediaData >>>', mediaData)
  const { play_url, playUrl, title, m_id, m_type } = mediaData
  let p = play_url || playUrl
  let m = m_id || -1
  let t = title || ''

  let result = {
    contentId: p.split(';')[0], // p_sxaimxd2408141005;m_sxaimxd2408141005
    mid: m, // 2318
    title: t // 铃儿响叮当（舞蹈版）
  }
  console.log('mediaData result >>>', mediaData)
  return result
}

// 获取播放串
function getPlayUrl(globalApi, mediaData, callback) {
  let data = setupMedia(mediaData)
  // const { data } = mediaData
  const contentId = data.contentId // p_sxaimxd2408141005
  console.log('PLAY AUTH contentId>>>>', contentId)

  localStorage.getString('epg_server', '').then((server_value) => {
    console.log('PLAY AUTH epg_server ' + server_value)
    console.log('PLAY AUTH request URL ' + server_value + '/EPG/interEpg/user/default/authorize')
    //* 拿 access_token 去  epg_server + 接口地址 做播放鉴权获取播放串
    provider.query(BuildConfig.token_uri).then(
      (value) => {
        // {"result":1,"data":[{"name":"user_token","_id":"51","value":"5@Q6oAzvyqyRysfiRh2bRX0136729851"}]}
        if (value.data) {
          globalApi
            .getPlayUrl(
              server_value + '/EPG/interEpg/user/default/authorize',
              {
                // cid: 'p_sxaimxd2501131001',
                // cid: 'JOYU0084000000020000000101630269',
                cid: data.contentId,
                tid: -1, // 栏目编号
                // tid: data.contentId, // 栏目编号
                // supercid: 's_sxaimxd2408141005', // 父集编号
                playType: '1', // 播放类型
                contentType: '0', // 内容类型
                businessType: '1', // 业务类型,
                idflag: '1'
              },
              {
                Authorization: value.data[0].value
              }
            )
            .then((res) => {
              console.log('PLAY AUTH epg_server ' + server_value)
              console.log(JSON.stringify(res), '10000 getstring')
              callback && callback(res)
            })
            .catch((err) => {
              console.log(JSON.stringify(err), '10000 error')
            })
        }
      },
      (error) => {}
    )
  })
}

export { authorize, toPay, getPlayUrl, setupMedia }
